package com.inner;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.util.EntityUtils;


public class HttpsUtil{
	private String jksUrl="";
	private static final String KEYPW = "654321";
	private static final String CHARSET = "UTF-8";
	private static final String CONTENT_TYPE_TEXT = "text/plain";
	private String url = "127.0.0.1";
	private DefaultHttpClient httpClient;
	private boolean needLog = true;
	private static HttpsUtil instance;
	private HttpsUtil() {}
	public static HttpsUtil getInstance() {
		if (instance == null) {
			instance = new HttpsUtil();
		}
		return instance;
	}

	public void initHttpClient() throws Exception {
		PoolingClientConnectionManager pccm = new PoolingClientConnectionManager();
		KeyStore trustStore = KeyStore.getInstance("jks");
		InputStream fis = null;
		try {
			fis = new FileInputStream(new File(jksUrl));
			trustStore.load(fis, KEYPW.toCharArray());
		} finally {
			try {
				if(fis!=null) fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		// 设置访问协议
		SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
		Scheme sch = new Scheme("https", 443 , socketFactory);
		pccm.getSchemeRegistry().register(sch);
		pccm.setDefaultMaxPerRoute(20); // 每个主机的最大并行链接数
		pccm.setMaxTotal(100); // 客户端总并行链接最大数
		this.httpClient = new DefaultHttpClient(pccm);
	}
	
	public String sendReq(String reqXML) {
		if(needLog)System.out.println("请求:"+reqXML);
		HttpResponse res = null;
		String result = null;
		try {
			HttpPost post = new HttpPost(this.url);
			StringEntity se = new StringEntity(reqXML,CHARSET);
			se.setContentType(CONTENT_TYPE_TEXT);
			se.setContentEncoding(CHARSET);
			post.setEntity(se);
			res = httpClient.execute(post);
			if (res.getStatusLine().getStatusCode() == 200) {
				// 获取返回数据
				HttpEntity entity = res.getEntity();
				result = EntityUtils.toString(entity,"UTF-8");
				if (entity != null) {
					InputStream instream = entity.getContent();
					instream.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if(needLog)System.out.println("返回:"+result);
		return result;
	}
	public void setJksUrl(String jksUrl) {
		this.jksUrl = jksUrl;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public void setNeedLog(boolean needLog) {
		this.needLog = needLog;
	}
	
}
